3.1 Objects What's an object? What's contained inside an object? objects contain variables (data, attributes) objects contain methods (operations, behaviors) DEMO (Book.java, create Book class) 3.4.2 Mutators and Accessors How should the data inside an object be protected? instance variables should be declared private private String title; private int pages; How can you access the data in an object if the data is private? mutators (setters) change the state of an object accessors (getters) read the state of an object public void setTitle(String title) public String getTitle() Why do the setters need to check for valid values? 3.4.1 Constructors How should constructors be implemented to avoid code duplication? constructors should call setter methods public Book(String title, int pages) 3.4.5 main How many main methods can you have? one in each class Why would you have a main method in each class you write? use main method for testing a class DEMO (test the Book class with main) 3.4.3 toString Why do classes need a toString method? DEMO (add toString to Book class) public String toString() 3.4.4 equals DEMO (Library.java, create Library class) use array of Objects constructor add method main for testing DEMO (add toString method to Library class) How would you modify add to prevent adding duplicates? DEMO (add duplicate objects) Why do classes need an equals method? DEMO (add equals to Book class) public boolean equals (Object rhs) the parameter is always type Object 3.5.3 instanceof DEMO (Video.java, add Video object to library) use existing Video class How do you make equals compare Books and Videos? use instanceof to avoid ClassCastException equals must work for any object passed in if (rhs instanceof Class) { 3.6 Packages What is the purpose of packages? packages are used to organize collections of classes How do you put classes you write into packages? DEMO (put Book, Video, Library classes into packages) put Library in library package put Book/Video in library.holdings package package library; package library.holdings; Why doesn't Library compile? DEMO (add imports for Book and Video) import library.holdings.Book; Why does Library still not compile? DEMO (put Book/Video in correct directory) javac library/Library.java When do you need to use -classpath with javac? when the current directory is not the root of the packages javac -classpath ../ Library.java What happens when you try to run the Library class? java Library Where does the Library class need to located? java library.Library When do you need to use -classpath with java? java -cp pathname library.Library